<template lang="pug">
  screen-wrapper(title="实时预览")
    .realTimeMonitor.h
      el-row.h(:gutter="10")
        el-col.h(:span="4" v-loading="orgLoading")
          el-card.h.box_com.flexWrapper.orgWrapper(:bodyStyle="{padding: 0, flex: 1}")
            p(slot="header")
              el-input(
                class="mb10 filterInput"
                placeholder="输入机构名称"
                v-model="orgFilterText"
              )
            el-scrollbar.h(
              class="scrollWrapper"
              wrap-class="scroll__wrap"
              view-class="scroll__view"
              :native='false'
              :noresize='false'
            )
              el-tree(
                ref="tree"
                :data="orgTree"
                node-key="id"
                default-expand-all
                :filter-node-method="orgFilterNode"
                @node-click="orgChose"
              )
        el-col.h.flexWrapper(:span="14")
          .box_com(style="flex: 1")
            video-play(:urlOrCode="playUrlOrCode || orgInfo.cameraIndexCode || ''" :deviceCode="orgInfo.deviceCode || playDeviceCode")
          .box_com(style="margin-bottom:0")
            vue-seamless-scroll(:data="recentPicture" :class-option="seamlessOptions" style="height: 146px")
              el-image(
                v-for="item in recentPicture"
                :key="item.ID"
                :src="item.URL"
                @mouseenter="animate = false"
                @mouseleave="animate = true"
                style="margin-right: 10px"
                :style="{height: picWidth + 'px', width: picWidth + 'px'}"
                fit="cover"
              )
        el-col.h(:span="6")
          el-card.box_com.h.flexWrapper(:bodyStyle="{padding: 0, flex: 1}" v-loading="compareLoading")
            h3(slot="header") 比对信息
            el-scrollbar(
              class="pendConWrapper"
              style="height: 552px;margin-top: 20px"
              wrap-class="pend__wrap"
              view-class="pend__view"
              :native='false'
              :noresize='false'
            )
              .compareBox(v-for="(item, index) in compares" :key="index")
                el-row(:gutter="10")
                  el-col(:span="7")
                  a-image(
                      :url="item.picUrl"
                      :preview="false"
                      height="84px"
                    )
                  el-col(:span="10")
                    h3
                      | {{item.name}}
                      el-tag.ml5(type="danger" size="mini" effect="dark"  v-if="item.faceStatus === 1") 戴口罩
                    p.f12 {{item.compareTime}}
                  el-col(:span="7")
                    a-image(
                      :preview="false"
                      :url="item.idcardPhoto"
                      height="84px"
                    )
</template>
<script>
import vueSeamlessScroll from 'vue-seamless-scroll'
import { VideoPlay, AImage } from '@/components'
import initWebSocket from '@/utils/socket'
import { mapGetters } from 'vuex'
import { getMonitorOrgListTree, getMonitorTopStatic, getMonitorCompare } from '@/api/minitor'
import ScreenWrapper from '../ScreenWrapper'

export default {
  name: 'RealTimeMinitor',
  components: {
    VideoPlay,
    AImage,
    ScreenWrapper,
    vueSeamlessScroll
  },
  watch: {
    orgFilterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'sysParams'])
  },
  data () {
    return {
      websock: null, // 图片websocket对象
      orgFilterText: '',
      orgTree: [],
      topSum: {},
      orgInfo: {},
      recentPicture: [],
      picWidth: 106,
      compares: [],
      compareLoading: false,
      orgLoading: false,
      playUrlOrCode: '',
      playDeviceCode: '',
      seamlessOptions: {
        step: 0.2, // 数值越大速度滚动越快
        limitMoveNum: 4, // 开始无缝滚动的数据量 this.dataList.length
        hoverStop: true, // 是否开启鼠标悬停stop
        direction: 2, // 0向下 1向上 2向左 3向右
        openWatch: true, // 开启数据实时监控刷新dom
        singleHeight: 0, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
        singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
        waitTime: 1000 // 单步运动停止的时间(默认值1000ms)
      }
    }
  },
  created () {
    this.getMonitorTopStatic()
    this.getOrgTree()
  },
  methods: {
    // 初始化weibsokcket, 实时图片
    initWebSocket (deviceCode) {
      const that = this
      const { userInfo } = that
      // eslint-disable-next-line
      const wsuri = `ws://${location.host}/medical-bs/pic/server/${userInfo.userId}`
      try {
        this.websock = initWebSocket({
          ws: wsuri,
          data: {
            deviceCode: deviceCode || '',
            top: 8,
            userId: userInfo.userId
          },
          msgCallback: function (res) {
            console.log(res)
            let recentPicture = that.recentPicture
            // 绑定收到消息事件
            if (res.respCode === 0 && res.respData) {
              let flag = false // 图片列表是否更新，判断是否重新获取对比信息
              if (res.respData.respData) {
                // 初次获取列表
                recentPicture = res.respData.respData
                flag = true
              } else if (!recentPicture.find(x => x.ID === res.respData.ID)) {
                // 之后推送单张图片对象，判断是否已经存在，不存在push进入数组
                recentPicture.unshift(res.respData)
                flag = true
              }
              // 获取对比信息
              if (flag) {
                that.recentPicture = recentPicture
                const picIds = recentPicture.map(x => { return x.ID })
                that.getMonitorCompare(picIds.join(','))
              }
            }
          }
        })
        // 离开路由之后断开websocket连接
        this.$once('hook:beforeDestroy', function () {
          this.websock.close()
        })
      } catch (e) {
        console.log(e)
      }
    },
    // 获取统计数据
    getMonitorTopStatic () {
      getMonitorTopStatic().then(res => {
        this.topSum = res.respData || {}
      })
    },
    // 获取左边机构树
    getOrgTree () {
      this.orgLoading = true
      getMonitorOrgListTree({ pid: this.$route.query.orgId ? this.$route.query.orgId : '' }).then(res => {
        this.orgTree = res.data || []
        this.orgInfo.deviceCode = res.deviceCode || ''
        this.orgInfo.cameraIndexCode = res.cameraIndexCode || ''
        this.orgInfo.orgId = res.orgId || ''
        if (res.deviceCode) {
          this.initWebSocket(res.deviceCode)
        }
      }).finally(() => {
        this.orgLoading = false
      })
    },
    // 机构删选
    orgFilterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 机构树点击选择
    orgChose (e) {
      if (e.xtype === 2 && (e.cameraIndexCode || e.rtspUrl)) {
        if (e.id) {
          this.initWebSocket(e.id)
          this.orgInfo.deviceCode = e.id
        }
        this.playUrlOrCode = e.cameraIndexCode
      }
    },
    // 比对信息
    getMonitorCompare (picIds) {
      if (!picIds && Array.isArray(this.recentPicture)) {
        picIds = this.recentPicture.map(x => { return x.ID }).join(',')
      }
      this.compareLoading = true
      getMonitorCompare({ busiTypes: 0, picIds }).then(res => {
        this.compares = res.respData || []
      }).finally(() => {
        this.compareLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.flexWrapper {
  display: flex;
  flex-direction: column;

 /deep/ .el-card__header{
   padding: 0;
   border-bottom: none
 }

 /deep/ .el-tree{
    background: transparent;
 }
}

.box_com{
  background: #021133;
  position: relative;
  border: 1px solid #112b68;
  padding: 10px;
  color:#D8D8D8;
  margin-bottom: 10px;
  box-sizing: border-box;

  h3 {
    color:#03a3de;
    font-size: 16px;
    position: relative;
    margin-bottom: 12px;

    .typeSwitch {
      position: absolute;
      right: 0
    }
  }
}

.orgWrapper {
  /deep/ .el-input__inner{
    background-color: transparent;
    border-color: #112b68;
    color: #fff;

    &:focus{
      border-color: $--color-primary
    }
  }
}

.scrollWrapper{
  overflow: hidden;
  position: relative;

  .scrollBox {
    white-space: nowrap;
    position: absolute;
    font-size: 0;
    z-index: 1;
  }

  &:hover{
    > span {
      display: block
    }
  }

  > span {
    display: none;
    position: absolute;
    cursor: pointer;
    top: 50%;
    line-height: 44px;
    transform: translateY(-50%);
    background: rgba(0,0,0,0.6);
    color: #fff;
    height: 40px;
    border-radius: 20px;
    width: 40px;
    text-align: center;
    z-index: 10;

    &:hover{
      background: rgba(0,9,27,0.8)
    }

    i {
      font-size: 18px
    }

    &.prev{
      left: 0
    }

    &.next{
      right: 0
    }
  }
}

.compareBox{
  margin-bottom: 10px;
  background: rgba(0,0,0,0.3);
  padding: 10px;

  h3 {
    margin-bottom: 8px
  }
}

</style>
